package com.jianli.smart.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DBUtil {
	private static final String driver = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/test";
	private static final String username = "root";
	private static final String password = "5989100";

	private static final Logger LOGGER = LoggerFactory.getLogger(DBUtil.class);
	private static ThreadLocal<Connection> connectionContainer = new ThreadLocal<Connection>();

	public static Connection getConnection() {
		Connection connection = connectionContainer.get();
		if (connection == null) {
			try {
				Class.forName(driver);
				connection = DriverManager.getConnection(url, username, password);

			} catch (Exception e) {
				LOGGER.error("数据库连接错误", e);
			} finally {
				connectionContainer.set(connection);
			}

		}
		return connection;
	}

	public static void closeConnection() {
		Connection connection = connectionContainer.get();

		try {
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			LOGGER.error("数据库连接关闭错误", e);
		} finally {
			connectionContainer.remove();
		}

	}
}
